<?php 
namespace app\admin\controller;
use think\Controller;

class Attr extends Controller{
	public function index(){
		$id = input('id');
		if($id){
			$map['type_id'] = ['=',$id];
		}else{
			$map = 1;
		}
		
		$attr_res = db('attr')->where($map)->select();
		$this->assign([
			'attr_res'	=>$attr_res,
		]);
		return view();
	}

	public function add(){
		if(request()->isPost()){
			$data = input('post.');
			$res = db('attr')->insert($data);
			if($res){
				$this->success('商品属性添加成功！',url('index'));
			}else{
				$this->error('属性类型添加失败！');
			}
		}
		$type_res = db('type')->select();
		$this->assign([
			'type_res'	=>$type_res,
		]);
		return view();
	}

	public function edit($id){
		$attr = db('attr');
		if(request()->isPost()){
			$data = input('post.');
			$res = $attr->update($data);
			if($res !== false){
				$this->success('属性编辑成功！',url('index'));
			}else{
				$this->error('属性编辑失败！');
			}
		}
		$attr_res = $attr->find($id);
		$type_res = db('type')->select();
		$this->assign([
			'attr_res'	=>$attr_res,
			'type_res'	=>$type_res,
		]);
		return view();
	}

	public function del($id){
		$res = db('attr')->delete($id);
		if($res){
			$this->success('属性删除成功！',url('index'));
		}else{
			$this->error('属性修改失败！');
		}
	}

	public function ajaxGetAttr(){
		if(request()->isPost()){
			$data = input('post.');
			$attrRes = db('attr')->where(['type_id'=>$data['type_id']])->select();
			echo json_encode($attrRes);
		}
	}
}